package org.mspring.mlog.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;

import freemarker.ext.jsp.TaglibFactory;
import freemarker.template.TemplateModelException;

/**
 * @author Gao Youbo
 * @since 2012-7-17
 */
public class DispatcherServlet extends org.mspring.platform.web.spring.DispatcherServlet {

    private static final long serialVersionUID = 8787317511980843719L;

    private static final Logger log = LoggerFactory.getLogger(DispatcherServlet.class);

    private static TaglibFactory factory = null;

    @Override
    protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception {
        exportWidgetTld(request, mv);
        super.render(mv, request, response);
    }

    /**
     * 将tag标签添加到环境变量
     *
     * @param request
     * @param mv
     */
    private void exportWidgetTld(HttpServletRequest request, ModelAndView mv) {
        try {
            if (factory == null) {
                factory = new TaglibFactory(request.getSession().getServletContext());
            }
            mv.getModel().put("m", factory.get("/WEB-INF/tld/mspring.tld"));
        } catch (TemplateModelException e) {
            log.error("加载TLD标签失败", e);
        }
    }
}
